import React, { useState } from 'react';
import { useTemplateContext } from '@/contexts/TemplateContext';
import { toast } from 'sonner';

const ImportTemplateModal: React.FC = () => {
  const { isImportTemplateOpen, closeImportTemplate, importTemplates } = useTemplateContext();
  const [fileContent, setFileContent] = useState('');
  const [error, setError] = useState('');
  
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    if (file.type !== 'application/json') {
      setError('请选择JSON格式的文件');
      return;
    }
    
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const content = event.target?.result as string;
        JSON.parse(content); // 验证JSON格式
        setFileContent(content);
        setError('');
      } catch (err) {
        setError('文件格式错误，不是有效的JSON');
        setFileContent('');
      }
    };
    reader.readAsText(file);
  };
  
  const handleImport = () => {
    if (!fileContent) {
      setError('请先选择有效的JSON文件');
      return;
    }
    
    try {
      const templatesData = JSON.parse(fileContent);
      importTemplates(templatesData);
      toast.success('模板导入成功');
      closeImportTemplate();
    } catch (err) {
      setError('导入失败，文件格式不正确');
    }
  };
  
  if (!isImportTemplateOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-2xl font-bold text-gray-800">导入模板</h2>
        </div>
        
        <div className="p-6 space-y-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              选择JSON格式的模板文件
            </label>
            <input
              type="file"
              accept=".json"
              onChange={handleFileChange}
              className="w-full p-3 border-2 border-dashed border-gray-300 rounded-md hover:border-blue-500 transition-colors"
            />
            
            {error && (
              <p className="mt-2 text-sm text-red-600">{error}</p>
            )}
            
            <div className="mt-4 p-4 bg-gray-50 rounded-md text-sm text-gray-600">
              <p className="font-medium mb-2">模板文件格式要求：</p>
              <pre className="whitespace-pre-wrap overflow-x-auto p-2 bg-gray-100 rounded">
{`{
  "template1": {
    "title": "模板标题",
    "fields": {
      "参数1": "",
      "参数2": ""
    },
    "content": "模板内容，使用{{参数1}}作为占位符"
  }
}`}
              </pre>
            </div>
          </div>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-b-lg flex justify-end gap-3">
          <button
            onClick={closeImportTemplate}
            className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleImport}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
            disabled={!fileContent || error}
          >
            导入模板
          </button>
        </div>
      </div>
    </div>
  );
};

export default ImportTemplateModal;